package cn.js.sangu.unitStore.service;

import cn.hutool.core.util.StrUtil;
import cn.js.sangu.unitStore.common.exception.ServiceException;
import cn.js.sangu.unitStore.dto.MailInfoDTO;
import cn.js.sangu.unitStore.dto.WebsiteInfoDTO;
import cn.js.sangu.unitStore.entity.Website;
import cn.js.sangu.unitStore.mapper.WebsiteMapper;
import cn.js.sangu.unitStore.utils.MailUtil;
import cn.js.sangu.unitStore.utils.TokenUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 说明：官网消息处理服务
 * 作者：linshuo
 */
@Slf4j
@Service
public class WebsiteService extends ServiceImpl<WebsiteMapper, Website> {

    @Autowired
    MailUtil mailUtil;


    public Website saveInfo(WebsiteInfoDTO dto){
        Website website = new Website();
        website.setInfoSource(dto.getInfoSource());
        website.setCompanyName(dto.getCompanyName());
        website.setContactName(dto.getName());
        website.setContactPhone(dto.getPhone());
        website.setContactMessage(dto.getMessage());
        website.setState("未处理");
        website.setRemark("客户IP："+dto.getIpAddr());
        if (!super.save(website)){
            throw new ServiceException("保存失败！请联系管理员");
        }
        return website;
    }

    public String updateInfo(Website website){
        if (!super.updateById(website)){
            throw new ServiceException("更新失败！请联系管理员");
        }

        MailInfoDTO dto = new MailInfoDTO();
        dto.setCompanyName(website.getCompanyName());
        dto.setName(website.getContactName());
        dto.setPhone(website.getContactPhone());
        //更新成功后，异步发送邮件

        String email = Objects.requireNonNull(TokenUtils.getCurrentUser()).getEmail();
        mailUtil.sendMail(dto,email);

        String res = "修改成功";
        if (StrUtil.isBlank(email)){
            res+=",但用户可能未设置邮箱信息";
        }
        return res;
    }

}
